import router from './router'
import { setPageTitle } from '@/utils/common'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Cookies from 'js-cookie'
import store from './store'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 退出登录
const logout = () => {
  store.dispatch('permission/resetPermission')
  store.dispatch('user/clearInfo')
}

//错误提示
const messageErrorTip  = (message) => {
  Message.error({
    title: '提示',
    message,
    duration: 3000
  })
}

// 路由白名单，白名单中的路由不需要校验登陆
const whiteList = ['login']
/**
 * 添加路由守卫，验证码规则和登录页不需要token，其他页面需判断token是否存在
 */
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // 设置title
  document.title = setPageTitle(to.meta.title)
  // 其他系统登出跳回商户登录
  if (to.path === '/login' && to.query.isLogout) {
    logout()
    return
  }
  const token = Cookies.get('token') || ''
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 判断是否已经获取权限，如果没有则调用获取权限方法，动态添加路由
      if (!store.state.permission.hasPermission) {
        // 获取需要添加的路由
        let newRoutes = await store.dispatch('permission/getNewRoute')
        //若没有获取到对应权限，可能是商户问题，退出到登录，不让进入死循环
        if(!newRoutes.length){
          messageErrorTip('权限异常，请登录重试！')
          logout()
          return
        }
        router.addRoutes(newRoutes)
        next({...to}) // replaceState
      } else {
        checkRouter( to.name, next )
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

//是否有页面，没有进入404
const checkRouter = (targetName,next) => {
  // 注释此处，是因为发现无权限页面to.name均为null,顾不需要在遍历路由
  // if(targetName === '404') return next()
  // const hasPage =  store.getters.routes.some(item=>{
  //   return item.name = targetName || item.children.map( item => item.name ).includes(targetName)
  // })
  if(targetName){
    next()
  }else{
    next('/404')
  }
}
